package cn.aylog.algorithm;

import java.util.Arrays;

/**
 * 快速排序
 */
public class QuickSort {
    public static void main(String[] args) {
        int arr[] = {8,9,1,7,2,2,5,4,6};
        // int len = 8;
        // int[] arr = new int[len];
        // for(int i=0; i<len; i++) {
        //     arr[i] = (int)(Math.random()*8000000);
        // }
        long start = System.currentTimeMillis();
        quickSort(arr, 0, arr.length-1); // 92 101 108
        long end = System.currentTimeMillis();
        System.out.println("排序耗时: " + (end - start));
        System.out.println(Arrays.toString(arr));

    }

    /**
     * 挖坑法
     */
    public static void quickSort2(int[] arr, int left, int right) {
        if(left > right) return;
        int l = left, r = right, pivot = arr[r]; // 挖坑r
        while(l < r) {
            while (arr[l] <= pivot && l < r) {
                l += 1;
            }
            arr[r] = arr[l]; // 挖坑l
            while (arr[r] > pivot && l < r) {
                r -= 1;
            }
            arr[l] = arr[r];// 挖坑r
        }
        arr[r] = pivot;
        quickSort(arr, left, l-1);
        quickSort(arr, r+1, right);
    }

    public static void quickSort(int[] arr, int left, int right) {
        if(left > right) return;
        int l = left, r = right, pivot = arr[(left+right)/2];
        int temp;
        while(true) {
            while (arr[l] < pivot) {
                l += 1;
            }
            while (arr[r] > pivot) {
                r -= 1;
            }
            if(l >= r) break;

            temp = arr[l];
            arr[l] = arr[r];
            arr[r] = temp;
            l++;
            r--;

        }
        quickSort(arr, left, l-1);
        quickSort(arr, r+1, right);
    }
}
